package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.City;
import cn.thornbird.orgsync.vo.request.CityQueryRequest;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
public class CitySpecification extends BaseSpecification<City> {

    private static final long serialVersionUID = -1926963450430368392L;

    private final CityQueryRequest cityQueryRequest;

    @Override
    public Predicate toPredicate(@NonNull Root<City> root, @NonNull CriteriaQuery<?> query,
                                 @NonNull CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        List<String> fields = Arrays.asList("name");
        predicates.add(toKeywordPredicate(cityQueryRequest.getKeyword(), fields, root, criteriaBuilder));
        if (!StringUtils.isEmpty(cityQueryRequest.getParentId())) {
            List<Predicate> parentIdPredicates = new ArrayList<>();
            parentIdPredicates.add(criteriaBuilder.equal(root.get("parentId"), cityQueryRequest.getParentId()));
            parentIdPredicates.add(criteriaBuilder.equal(root.get("id"), cityQueryRequest.getParentId()));
            predicates.add(criteriaBuilder.or(parentIdPredicates.toArray(new Predicate[0])));
        }
        return toPredicate(criteriaBuilder, predicates);
    }

}
